import React, { useRef,useEffect ,useState,forwardRef,useImperativeHandle} from 'react'
import { withRouter } from 'react-router-dom'
import MyTable from '@/components/common/table'
import Role from '@/api/role'
import Menu from '@/api/menu'
import $axios from '@/utils/axios'
import {  getQuery } from '@/assets/js/publicFunc'
import { Button,Modal,Form,Spin,Result} from 'antd'
import { modalLayoutSm } from '@/config/layout'
import getFtypeObj,{Ftype} from '@/config/ftypes'
import moment from 'moment';

const Commonlist = () => {
  const tableRef: RefType = useRef()
  const rowEdit: RefType = useRef()
  const query = getQuery()
  const { type } = query
  const fTypeObj = getFtypeObj(type);
  const operation_id = fTypeObj['operation_id'];
  
  const [columns,setcolumns] = useState([]);
  const [isError,setIsError] = useState(false);
  useEffect(()=>{
    let newcolumns = [];
    let isErrorBool = getFtypeObj(type)?false:true;
    setIsError(isErrorBool);
    if(!isErrorBool){
      let listColumns = fTypeObj['listColumns']?fTypeObj['listColumns']:[]
      listColumns.map((e,i)=>{
        switch(e['type']){
          case 'serialNumber':
            newcolumns.push(  {
              title: '序号',
              dataIndex: 'index',
              render:(text,record,index)=>{
                return index+1
              }});
            break;
          case 'string'://字符串
            newcolumns.push(  {
              title: e['title'],
              dataIndex: e['key'],
              key:e['key'],
              render:(text,record,index)=>{
                return text
              }});
            break;
          case 'moment'://日期
            newcolumns.push(  {
              title: e['title'],
              dataIndex: e['key'],
              key:e['key'],
              render:(text,record,index)=>{
                return text?moment(text).format(e['fotmat']):''
              }});
            break;
          case 'operation'://操作
            newcolumns.push(  {
              title: '操作',
              align: 'center',
              dataIndex: 'operation',
              width:e['width']?e['width']:'auto',
              render:(text,record,index)=>{
                return <div>
                  <Button className="btn" onClick={()=>edit(record[operation_id])} size="small">编辑</Button>
                  <Button style={{marginLeft:'10px'}} className="btn" onClick={()=>del(record[operation_id])} size="small">删除</Button>
                
                </div>
              }
            });
            break;
          case 'custom':
            newcolumns.push(  {
              title: e['title'],
              align: 'center',
              dataIndex: e['key'],
              key:e['key'],
              render:e['render']
            });
          
            break;
          default:
            break;
        }
        return 1
      })
    
      setcolumns(newcolumns);
    }
    
  },[])
  // 添加
  const add = () => {
    rowEdit.current.init('');
  }
   // 修改
   const edit = (id) => {
    rowEdit.current.init(id);
  }
  // 删除
  const del = (id) => {
    Modal.confirm({
      title: '确认删除？',
      
      onOk() {
        let params:object = {
          
        }
        let key = fTypeObj['params_id_key']?fTypeObj['params_id_key']:operation_id
        let actionType = fTypeObj['deleteActionType']=='array'?true:false;
        let isBody = false;
        if(actionType){
          let list = [id];
          key = fTypeObj['deleteActionKey']?fTypeObj['deleteActionKey']:operation_id;
          isBody = true;
          params[key] = list;
          params['isBody'] = true;
        }else{
          params[key] = id;
        }
        let fn = fTypeObj['delMethod']?$axios[fTypeObj['delMethod']]:$axios.delete
        fn(fTypeObj['delUrl'],params).then(()=>{
          tableRef.current.update();
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  const getList = (params)=>{
    let fn = fTypeObj['listMethod']?$axios[fTypeObj['listMethod']]:$axios.get

     return fn(fTypeObj['listUrl'], params)
  }
  return (
      <>
      {
        isError? <Result
        style={{ height: '100vh' }}
        status="500"
        title="500"
        subTitle="您还未定义内容，请先配置内容"
      />:<div id="commonListWrapId"> <div style={{overflow:'hidden'}}><Button className="fr" onClick={add} style={{marginBottom:'15px'}} type="primary">
          {fTypeObj['addTxt']}
        </Button></div>
        <MyTable
          apiFun={getList}
          columns={columns}
          ref={tableRef}
        />
        <CommonEditCom ref={rowEdit} callback={()=>{
          tableRef.current.update();
        }}/>
      </div>
      }
      </>
      
  )
}

//新建/修改
const CommonEdit = (props,refs) => {
  const [loading, setLoading] = useState<boolean>(false)
  //显示隐藏弹窗
  const [isModalVisible, setIsModalVisible] = useState(false);
   //显示隐藏树
   const [isTreeVisible, setIsTreeVisible] = useState(false);
   //默认选中
   const [defauleChecked,setdDefaultCheck] = useState([]);
  //橘色is
  const [roleId,setId] = useState('');
  //form
  const [form] = Form.useForm()
  const { setFieldsValue, resetFields } = form
  //菜单树
  const [treeData,setTreeData] = useState<any[]>([]);
  const query = getQuery()
  const { type } = query
  const fTypeObj = getFtypeObj(type);
  const operation_id = fTypeObj['operation_id'];
  useImperativeHandle(refs, () => ({
    init: (id) => {
      setId(id);
      if(id){
        getDetail(id);
      }else{
        resetFields();
        showModal();
        setdDefaultCheck([]);
        setIsTreeVisible(true)
      }
     
    }
  }))
  //获取详情
  const getDetail = (id)=>{
    let key = fTypeObj['params_id_key']?fTypeObj['params_id_key']:operation_id;
    let params = {};
    params[key] = id;
    $axios.get(fTypeObj['detailUrl'], params).then((res)=>{
      let edilFields = fTypeObj['edilFields'];
      let setFields = {};
      edilFields.map((e)=>{
        setFields[e['key']] = res.data[e['key']];
        return 1
      })
      setFieldsValue(setFields);
      setIsTreeVisible(true)
      showModal();
    })
  }
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };
  //确定
  const handleOk = () => {
    form.validateFields().then((vals) => {
      const Obj = form.getFieldsValue()
      setLoading(true)

      const url = roleId===''?fTypeObj['addUrl']:fTypeObj['editUrl'];
      const params = {
        ...Obj
      };
      let fn = $axios.post
      if(roleId){
        let key = fTypeObj['update_id_key']?fTypeObj['update_id_key']:operation_id
        params[key] = roleId;
        fn = $axios[fTypeObj['editMethod']];
      }
       
      fn(url, params).then((res)=>{
        handleCancel();
      })
    }).catch(info => {
      
    })
  };
  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setId('');
    setLoading(false);
    setIsTreeVisible(false);
    props.callback&&props.callback();
  };
  const handleSubmit = () => {
    
    setTimeout(() => {
      setLoading(false)
      
    }, 1000)
  }
  const onSelect = (selectedKeys: React.Key[], info: any) => {
    console.log('selected', selectedKeys, info);
  };

  const onCheck = (checkedKeys, info: any) => {
    console.log('onCheck', checkedKeys, info);
    setFieldsValue({
      menuids:checkedKeys
    });
  }; 
  const getFields = (): JSX.Element[] => {
    const query = getQuery()
    const { type } = query
    const fTypeObj = getFtypeObj(type);
    const list = fTypeObj['edilFields']?fTypeObj['edilFields']:[];
    return list.map((item: CommonObjectType) => {
      return (
        <Form.Item
          key={item.key}
          name={item.key}
          rules={item.rules}
          label={item.label}
          style={{ marginBottom: '6px' }}
        >
          {item.slot}
        </Form.Item>
      )
    })
  }
  return <Modal 
    title={Ftype[type]+"设置"} 
    visible={isModalVisible} 
    onOk={handleOk} 
    onCancel={handleCancel}
    width={600}
    maskClosable={false}
    getContainer={document.getElementById('commonListWrapId')}
    mask={false}
    centered
    >

    <Spin spinning={loading}>
      <Form {...modalLayoutSm} form={form} onFinish={handleSubmit}>
        {
          getFields()
        }
      </Form>
    </Spin>
     
</Modal>
}

const CommonEditCom = forwardRef(CommonEdit);
export default withRouter(Commonlist)
